package com.shebao.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shebao.bean.Company;
import com.shebao.dao.SBCompanyDao;
import com.shebao.dao.SBPersonDao;
import com.shebao.entity.SBCompanyEntity;
import com.shebao.entity.SBPersonEntity;
import com.shebao.utils.FileUtil;
import com.shebao.utils.PersonalProvePDFUtil;
import com.shebao.utils.ResultUtil;

@Service
public class PersonService {
	@Autowired
	private SBPersonDao sBPersonDao;
	@Autowired
	private PersonalProvePDFUtil personalProvePDFUtil;
	@Autowired
	private FileUtil fileUtil;
	@Autowired
	private SBCompanyDao sBCompanyDao;
	
	public String findPerson(Integer selectType,String selectCode){
		if(null==selectType){
			return ResultUtil.fail("缺少查询条件selectType！");
		}
		if(StringUtils.isBlank(selectCode)){
			return ResultUtil.fail("缺少查询条件selectCode！");
		}
		SBPersonEntity personEntity=null;
		if(1==selectType){//通过社保编码查询
			personEntity=sBPersonDao.findBySocialId(selectCode);
		}else{//通过身份证查询
			personEntity=sBPersonDao.findByCardId(selectCode);
		}
		
		if(null==personEntity){
			return ResultUtil.fail("无该记录！");
		}
		
		return ResultUtil.success(personEntity);
	}
	
	public byte[] printPerson(Integer selectType,String selectCode){
		
		byte[] bos=null;
		List<SBPersonEntity> list=null;
		if(1==selectType){//通过社保编码查询
			list=sBPersonDao.listBySocialId(selectCode);
		}else{//通过身份证查询
			list=sBPersonDao.listByCardId(selectCode);
		}
		
		//进行倒序
		Collections.reverse(list);
		try {
			String outPath=personalProvePDFUtil.createPDF(list,companyjs(list));
			bos=fileUtil.read(outPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bos;
	}
	
	//单位信息计算
	private String companyjs(List<SBPersonEntity> list){
		if(null==Company.map){
			List<SBCompanyEntity> cls= sBCompanyDao.list();
			Company.map=new HashMap<Long, String>();
			for(SBCompanyEntity c:cls){
				Company.map.put(c.getCompanyId(), c.getCompanyName());
			}
		}
		List<Long> sortList=new ArrayList<Long>();
		Set<Long> qcset=new HashSet<Long>();
		for(SBPersonEntity pe:list){
			Long a=pe.getCompanyId();
			if(0==a){
				continue;
			}
			if(!qcset.contains(a)){
				sortList.add(a);
				qcset.add(a);
			}
		}
		StringBuilder sb=new StringBuilder();
		//拼接支付传
		for(int i=0;i<sortList.size();i++){
			Long a=sortList.get(i);
			String b=Company.map.get(a);
			sb.append(a).append(" ").append(b);
			if(sortList.size()==(i+1)){
				sb.append("。");
			}else{
				sb.append("；");
			}
		}
		return sb.toString();
	}
}
